package com.situ.mall.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.ramostear.captcha.HappyCaptcha;
import com.situ.mall.admin.entity.Administrator;
import com.situ.mall.admin.mapper.AdministratorMapper;
import com.situ.mall.admin.service.IAdministratorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.admin.util.RequestUtil;
import com.situ.mall.base.exception.InfoException;
import com.situ.mall.base.util.AvatarUtil;
import com.situ.mall.base.util.C;
import com.situ.mall.base.util.Md5Util;
import com.situ.mall.base.util.URLUtil;
import com.situ.mall.base.vo.ResVO;
import com.situ.mall.base.vo.LayuiTableVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author darling
 * @since 2023-03-17
 */
@Service
public class AdministratorServiceImpl extends ServiceImpl<AdministratorMapper, Administrator> implements IAdministratorService {

    // 根据用户名查询管理员信息
    @Override
    public Administrator selectByUsername(String username) {
        return baseMapper.selectByUsername(username);
    }

    // 上传头像
    @Override
    public synchronized ResVO avatar(MultipartFile file) {
        AvatarUtil avatarUtil = new AvatarUtil();
        String path = C.AVATAR_PATH;
        String filename = System.currentTimeMillis() + C.PNG;
        return avatarUtil.avatar(file, path, filename);
    }

    // 所有管理员
    @Override
    public LayuiTableVO doList(Integer page, Integer limit, String keyword) {
        PageHelper.startPage(page, limit);
        return LayuiTableVO.data(baseMapper.doList(keyword));
    }

    // 验证登录
    @Override
    public boolean check(String username, String password) {
        Administrator administrator = baseMapper.check(username);
        if (null != administrator) {
            if (administrator.getPassword().equals(Md5Util.md5(password))) {
                RequestUtil.setCurrent(administrator);
                return true;
            }
            throw new InfoException("用户名或密码错误！", 500);
        }
        throw new InfoException("当前管理员不可用", 500);
    }

    // 校验旧密码
    @Override
    public void verify(String oldPwd, String newPwd) {
        Administrator administrator = selectByUsername(Objects.requireNonNull(RequestUtil.getCurrent()).getUsername());
        if (null != administrator) {
            boolean b = administrator.getPassword().equals(Md5Util.md5(oldPwd));
            if (!b) {
                throw new InfoException("旧密码错误", 500);
            } else {
                baseMapper.changePwd(Md5Util.md5(newPwd), administrator.getId());
            }
        }
    }


}
